package com.hhj.sharding.sphere.demo.controller;

import cn.hutool.core.util.RandomUtil;
import com.hhj.sharding.sphere.demo.base.PageVO;
import com.hhj.sharding.sphere.demo.base.Result;
import com.hhj.sharding.sphere.demo.model.OrderParamVO;
import com.hhj.sharding.sphere.demo.model.UserParamVO;
import com.hhj.sharding.sphere.demo.model.entity.User;
import com.hhj.sharding.sphere.demo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;

/**
 * 用户接口
 *
 * @Description
 * @Author HHJ
 * @Date 2022-02-28 18:28
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 测试分库分表-分页
     */
    @PostMapping("/findPage")
    public Result<PageVO> findPage(@RequestBody UserParamVO req) {
        log.info("测试分库分表1-用户分页");
        return Result.success(userService.findPage(req));
    }

    /**
     * 测试分库分表-新增
     */
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody UserParamVO req) {
        log.info("测试分库分表1-用户新增");
        userService.save(buildOrder(null, "1" + RandomUtil.randomLong(0, 10000000), "1" + RandomUtil.randomLong(0, 10000000), req.getUserPhone()));
        return Result.success(true);
    }

    /**
     * 测试分库分表 - 修改
     */
    @PostMapping("/updateById")
    public Result<Boolean> updateById(@RequestBody User req) {
        log.info("测试分库分表1- 用户修改");
        userService.updateById(buildOrder(req.getId(), req.getUserName(), req.getUserEmail(), req.getUserPhone()));
        return Result.success(true);
    }

    /**
     * 测试分库分表- 删除
     */
    @PostMapping("/deleteById")
    public Result<Boolean> deleteById(@RequestBody UserParamVO req) {
        log.info("测试分库分表1- 用户删除");
        boolean b = userService.removeById(req.getId());
        return Result.success(b);
    }

    private User buildOrder(Long id, String userName, String userEmail, String code) {
        User entity = new User();
        entity.setId(id);
        entity.setUserName(Objects.nonNull(userName) ? userName.toString() : "");
        entity.setUserEmail(Objects.nonNull(userEmail) ? userEmail.toString() : "");
        entity.setUserPhone(code);
        return entity;
    }

}
